#!/bin/bash

set -e
ENTRY_ARG="${1}"
BUILD_PATH="$(pwd)"
export TOOLS="${BUILD_PATH}/tools"
source "${BUILD_PATH}/config.sh"
source "${BUILD_PATH}/tools/utils.sh"


## install obs
if [[ x"${ENTRY_ARG}" == x"install_obs" ]]; then
    set +e
    sshscp "${BUILD_PATH}/install_obs/install_obs.sh" "/opt"
    sshcmd "cd /opt; bash install_obs.sh"
fi

## setp2
if [[ x"${ENTRY_ARG}" == x"middleware" ]]; then
    # make source.tar.gz and tools_tar.gz
    bash "${BUILD_PATH}/source_download/mk_tools.sh" "${EULEROS_VERSION}" "${BUILD_TIME}"
    if [ $? != 0 ]; then
        echo "make source.tar.gz and tools_tar.gz failed"
        return 1
    fi
    sshcmd "rm -f /opt/${EULEROS_VERSION}_TOOLS.tar.gz /opt/${EULEROS_VERSION}_SOURCE.tar.gz /opt/standard.tar.gz"
    sshscp "${EULEROS_VERSION}_TOOLS.tar.gz" "/opt"
    sshscp "${EULEROS_VERSION}_SOURCE.tar.gz" "/opt"
    # obsserver get fedora_baseline tar package
    sshcmd "cd /opt; wget http://10.120.107.75/fedora_baseline/standard.tar.gz &> /dev/null"
    # version_build on obsserver
    SSHCMD_TOOL="cd /opt; tar -xf ${EULEROS_VERSION}_TOOLS.tar.gz; cd /opt/${EULEROS_VERSION}_TOOLS; bash -x euleros_server_v200r008c00.sh version_build ${OBSSERVER_IP} root@${OBS_AGENT}:${OBSPASSWD} ${EULEROS_VERSION}"
    sshcmd "${SSHCMD_TOOL}"
fi

## cmc_file_download
if [[ x"${ENTRY_ARG}" == x"BepCloud" ]]; then
    BVERSION=$(echo "${EULEROS_VERSION}" |awk -F '_' '{ print $3 }')
    sed -i "s#V200R008C00B180#${BVERSION}#g" "${BUILD_PATH}/cmc_file_download/conf/Dependency.xml"
    bash "${BUILD_PATH}/cmc_file_download/cmc_file_download.sh"
    rm -rf "/usr1/bepcloud/rebuild/release/"; mkdir -p "/usr1/bepcloud/rebuild/release/"
    sshscp_from "/srv/www/htdocs/internal_use_only/EulerOS/EulerOS_V200R008C00/EulerOS_V200R008C00_ARM64/release" ./
    peer_path=$(cat release | sed "s#http://"${OBSSERVER_IP}"#/srv/www/htdocs#")
    sshscp_from "${peer_path}" "/usr1/bepcloud/rebuild/release/"
fi
